package root.controller.administration;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import net.arnx.jsonic.JSON;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.ThrowableUtil;

import root.model.Note;
import root.service.OnetimeService;
import root.until.RequestAction;

public class ListController extends Controller {
    OnetimeService oService = new OnetimeService();

    @Override
    public Navigation run() throws Exception {
        String action = request.getParameter("action");
        if (action != null) {
            if (action.equals(RequestAction.GET_NOTE)) {

                List<Note> rtData = oService.getListNote();
                if (rtData != null) {
                    Map<String, Object> data =
                        oService.formatDataResponse(rtData.size(), rtData);
                    this.json(data);
                }
            } else if (action.equals(RequestAction.SHOW_NOTE)) {

            }
            return null;
        }

        return forward("list.jsp");
    }

    /**
     * encode json
     * 
     * @author tuvv
     * @param data
     *            : Object
     * @return
     * 
     * */
    private void json(Object data) {
        String encoding = request.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }
        response.setContentType("application/json; charset=" + encoding);
        try {
            PrintWriter out = null;
            try {
                out =
                    new PrintWriter(new OutputStreamWriter(
                        response.getOutputStream(),
                        encoding));
                out.print(JSON.encode(data));
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (IOException e) {
            ThrowableUtil.wrapAndThrow(e);
        }
    }
}
